<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<el-form-item label="边坡名字" prop="slopeId">
        <el-select v-model="queryParams.slopeId" placeholder="请选择边坡编号" clearable style="width: 200px">
          <el-option
              v-for="dict in slopeCodeList"
              :key="dict.label"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备SN" prop="deviceSn">
        <el-input
            v-model="queryParams.deviceSn"
            placeholder="请输入设备SN"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间范围" prop="deviceSn">
        <el-date-picker
            v-model="queryParams.startTime"
            type="datetime"
            placeholder="开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
            @keyup.enter="handleQuery"
        />
        <el-date-picker
            v-model="queryParams.endTime"
            type="datetime"
            placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="primary"-->
      <!--            plain-->
      <!--            icon="Plus"-->
      <!--            @click="handleAdd"-->
      <!--            v-hasPermi="['data:soil:add']"-->
      <!--        >新增</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="success"-->
      <!--            plain-->
      <!--            icon="Edit"-->
      <!--            :disabled="single"-->
      <!--            @click="handleUpdate"-->
      <!--            v-hasPermi="['data:soil:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="danger"-->
      <!--            plain-->
      <!--            icon="Delete"-->
      <!--            :disabled="multiple"-->
      <!--            @click="handleDelete"-->
      <!--            v-hasPermi="['data:soil:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['data:soil:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="app-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="box-card">
            <div class="text-center">
              <span>时间范围：{{ queryParams.startTime }} ~ {{ queryParams.endTime }}</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="text-center">
              <span>土壤含水量占比平均值：{{ averageCrackChange }}%</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="text-center">
              <span>土壤含水量占比绝对最大值：{{ absoluteMaxCrackChange }}%</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="text-center">
              <span>土壤含水量占比均方根值：{{ rootMeanSquareCrackChange }}%</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-table v-loading="loading" :data="soilList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<el-table-column label="边坡名称" fixed="left" align="center" prop="slopeId" width="280px">
        <template #default="scope">
          <dict-tag :options="slopeCodeList" :value="scope.row.slopeId"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="逻辑主键ID" align="center" prop="id" />-->
      <el-table-column label="设备SN" align="center" prop="deviceSn" />
      <el-table-column label="数据时间" align="center" prop="createTime" />
<!--      <el-table-column label="地面以下所监测层位土壤中的温度(°C)" align="center" prop="soilTemperature" />-->
            <el-table-column label="土壤湿度（%）" align="center" prop="soilMoistureRatio0" />
      <el-table-column label="土壤湿度（%）" align="center" prop="soilMoistureRatio1" />
      <el-table-column label="土壤湿度（%）" align="center" prop="soilMoistureRatio2" />
      <el-table-column label="土壤湿度（%）" align="center" prop="soilMoistureRatio3" />
      <el-table-column label="土壤湿度（%）" align="center" prop="soilMoistureRatio4" />
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template #default="scope">-->
      <!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['data:soil:edit']">修改</el-button>-->
      <!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['data:soil:remove']">删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改土壤温度和水分占比监测数据对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="soilRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备SN" prop="deviceSn">
          <el-input v-model="form.deviceSn" placeholder="请输入设备SN" />
        </el-form-item>
        <el-form-item label="地面以下所监测层位土壤中的温度(°C)" prop="soilTemperature">
          <el-input v-model="form.soilTemperature" placeholder="请输入地面以下所监测层位土壤中的温度(°C)" />
        </el-form-item>
        <el-form-item label="土壤中水分占有体积和土壤总体积比值（%）" prop="soilMoistureRatio">
          <el-input v-model="form.soilMoistureRatio" placeholder="请输入土壤中水分占有体积和土壤总体积比值（%）" />
        </el-form-item>
        <el-form-item label="管养单位" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入管养单位" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Soil">
import {listSoil, getSoil, delSoil, addSoil, updateSoil} from "@/api/slope/data/soil";
import {listCrack} from "@/api/slope/data/crack.js";
import {listSlopeCode} from "@/api/slope/info/info.js";

const {proxy} = getCurrentInstance();

const soilList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const slopeCodeList = ref([]);


const fullDataList = ref([]);

const averageCrackChange = computed(() => {
  if (fullDataList.value.length === 0) return 0;
  const total = fullDataList.value.reduce((sum, item) => sum + item.soilMoistureRatio0+ item.soilMoistureRatio1+ item.soilMoistureRatio2+ item.soilMoistureRatio3+ item.soilMoistureRatio4, 0);
  return (total / (fullDataList.value.length*5)).toFixed(2);
});

const absoluteMaxCrackChange = computed(() => {
  if (fullDataList.value.length === 0) return 0;
  return Math.max(
      ...fullDataList.value.flatMap(item => [
        Math.abs(item.soilMoistureRatio0),
        Math.abs(item.soilMoistureRatio1),
        Math.abs(item.soilMoistureRatio2),
        Math.abs(item.soilMoistureRatio3),
        Math.abs(item.soilMoistureRatio4)
      ])
  ).toFixed(2);
});

const rootMeanSquareCrackChange = computed(() => {
  if (fullDataList.value.length === 0) return 0;

  let sumSquares = 0;
  let count = 0;

  fullDataList.value.forEach(item => {
    for (let i = 1; i <= 5; i++) {
      const val = item[`soilMoistureRatio${i}`];
      if (val != null) {
        sumSquares += val * val;
        count++;
      }
    }
  });

  if (count === 0) return 0;

  const meanSquare = sumSquares / count;
  return Math.sqrt(meanSquare).toFixed(2);
});


const data = reactive({
  form: {},
  queryParams: {
    slopId:"",
    pageNum: 1,
    pageSize: 10,
    deviceSn: null,
  },
  rules: {
    deviceSn: [
      {required: true, message: "设备SN不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询土壤温度和水分占比监测数据列表 */
function getList() {
  loading.value = true;
listSlopeCode().then(response => {
    // 假设 response 是一个普通的对象
    slopeCodeList.value = Object.entries(response).map(([key, value]) => ({
      label: key,
      value: value
    }))
  })

  listSoil(queryParams.value).then(response => {
    soilList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  const allParams = {...queryParams.value, pageNum: 1, pageSize: 1000000000}; // 根据后端最大限制设置
  listSoil(allParams).then(response => {
    fullDataList.value = response.rows;
  });
}


// 获取全部数据（用于统计）


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deviceSn: null,
    soilTemperature: null,
    soilMoistureRatio: null,
    deptId: null,
    createTime: null
  };
  proxy.resetForm("soilRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.startTime = null;
  queryParams.value.endTime = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加土壤温度和水分占比监测数据";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSoil(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改土壤温度和水分占比监测数据";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["soilRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSoil(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSoil(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除土壤温度和水分占比监测数据编号为"' + _ids + '"的数据项？').then(function () {
    return delSoil(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('data/soil/export/soilMoistureRatio', {
    ...queryParams.value
  }, `soil_${new Date().getTime()}.xlsx`)
}

getList();
</script>
